function [ net] = AdaptNN( input,target,net,neurons,initialKrills,NumberRuns,IterationMax )
%% Prepare time series
%% Input Serie and target
Total=NumberRuns*IterationMax;
global Ticker
name=strcat('Creating initial Population...',Ticker);
h = waitbar(0, name);%progress bar

target=target';
input=input';
input=[zeros(numel(input(:,1)),1) input(:,1:end-1) ];
Q = length(target);
P = zeros(5,Q);%Create a matrix of 5 files and 201 columns Num Windows, NumWindows=5
P(1,2:Q) = target(1,1:(Q-1));%Copy the target in P moved in 1 position to the right,Perdemos la ultima
P(2,3:Q) = target(1,1:(Q-2));%Copy the target in P moved in 2 position to the right en l asegunda fila
P(3,4:Q) = target(1,1:(Q-3));
P(4,5:Q) = target(1,1:(Q-4));
P(5,6:Q) = target(1,1:(Q-5));
P=P(:,6:end);
T=target;
T=T(:,6:end);

%% Normalization Data
%normalize input between 1,-1
[P,settings]=mapminmax(P);
[T,settingsTarget]=mapminmax(T);
%% Start

NumberKrills=initialKrills;
NumberParameters= net.numWeightElements;%22 , 15+3 second layer+3bias+1 bias
UpperLimit=max(P(1,:))*ones(1,NumberParameters);%1
LowerLimit=-max(P(1,:))*ones(1,NumberParameters);%-1
%NumberRuns=3;
%IterationMax=20;% maximun number of iterations per Run
C_flag = 1;                               % Crossover flag [Yes=1]
M_flag=1;
%Constants
Nmax=0.01;
Vf=0.02;
Dmax=0.008;% between 0.002 and 0.01
%Variables
X=zeros(NumberParameters,initialKrills);
F = zeros(NumberParameters,NumberKrills);D = zeros(1,NumberKrills);N = zeros(NumberParameters,NumberKrills);
%% Positions of krills
for numberRun=1:NumberRuns % Repeats all the process the times we wantesd
%Run = numberRun %to know where we are

krill=1;% the first krill hast previous net values
X(:,krill)= createParameters( net,neurons,P,T);
%at the begining is the best value
output=sim(net,P);
%output=net(P);
K(krill)=fitness(net,T,output);%%<============FITNESS=================
Kinitial=K(krill);


for krill=2:(NumberKrills)/2
    
for parameter = 1:NumberParameters%X has in row 1 x1 , in row2 x2.| Every column=1 krill
    X(parameter,krill)=LowerLimit(parameter)+(UpperLimit(parameter)-LowerLimit(parameter)).*rand();%1,NumberKrills
end
[net] = createNet( X(:,krill),neurons,P,T,net );
output=sim(net,P);
%output=net(P);
K(krill)=fitness(net,T,output);%%<============FITNESS=================


end
%if random we get better values...best for us
[Kbest(1,numberRun) numberkrill] = min(K);%get the best finest(Minimun)
Xbest(:,1,numberRun)= X(:,numberkrill);
[Kworst positionWorst] = max(K);
Kworst_Kbest = Kworst-Kbest(1,numberRun);

for krill=((NumberKrills)/2)+1:NumberKrills%Mutation of best
                M_rate = 0.6 + 0.4*(K(1)-Kbest(1,numberRun))/Kworst_Kbest;
                Mr = rand(NumberParameters,1) < M_rate ;
                RandomValues = rand(NumberParameters,1);
                X(:,krill)=RandomValues.*(1-Mr)+X(:,1).*Mr;
                [net] = createNet( X(:,krill),neurons,P,T,net );
                output=sim(net,P);
%output=net(P);
                K(krill)=fitness(net,T,output);%%<============FITNESS=================
               
end
    

    Kold=K;
    Xold=X;

%Here i have all the initial population with his output
[Kbest(1,numberRun) numberkrill] = min(K);%get the best finest(Minimun)
Xbest(:,1,numberRun)= X(:,numberkrill);




%% Motion Calculation
for iteration = 1:IterationMax;
    Iteration= iteration;
    name=strcat('Adapting.......',Ticker);
    waitbar(((numberRun-1)*IterationMax+iteration)/Total,h,name);

    %Food Motion
    for parameter = 1:NumberParameters;
            Numerator(parameter) = (sum(X(parameter,:)./K));%Sumatory of the location of food-NUM
    end
     Xfood(:,iteration) = Numerator./(sum(1./K)); %Food Location 
     Xfood(:,iteration) =findlimits(Xfood(:,iteration)',LowerLimit,UpperLimit,Xbest(:,iteration,numberRun)');% Bounds Checking
     % With weights , create a network to know error <==== FITNESS
     [net] = createNet( Xfood(:,iteration),neurons,P,T,net ); 
output=sim(net,P);
%output=net(P);
     Kfood(iteration)=fitness(net,T,output);%%<============FITNESS=================
     %Kfood(iteration) = fitness(Xfood(:,iteration));%%<============FITNESS=================
     
        if 2<=iteration% if new result is greater , we will stay in the last
            if Kfood(iteration-1)<Kfood(iteration)
                Xfood(:,iteration) = Xfood(:,iteration-1);
                Kfood(iteration) = Kfood(iteration-1);
            end
        end

   %% Others- Neighbours  
       [Kbest2 positionBest] = min(K);
       [Kworst positionWorst] = max(K);
        
        Kworst_Kbest = Kworst-Kbest(iteration,numberRun);
        
        w = (0.1+0.8*(1-iteration/IterationMax));%inertia weight

%% Movement
     for krill = 1:NumberKrills
     % Relative distances
            Rfood = Xfood(:,iteration)-X(:,krill);%distance every krill with food
            RbestKrill = Xbest(:,iteration,numberRun)-X(:,krill);%distance every krill with best
            for ii = 1:NumberKrills%distance every krill with every other
                Rkrillkrill(:,ii) = X(:,ii)-X(:,krill);
            end
            Rkrill = sqrt(sum(Rkrillkrill.*Rkrillkrill));
                 % % % % % % % % % % % % % Movement Induced % % % % % % % % % % % % %
            % Calculation of BEST KRILL effect
            if Kbest(iteration,numberRun) < K(krill) % Alpha target for the rest
                alpha_b = -2*(1+rand*(iteration/IterationMax))*(Kbest(iteration,numberRun) - K(krill)) /Kworst_Kbest/ sqrt(sum(RbestKrill.*RbestKrill)) * RbestKrill;
            else
                alpha_b=0;
            end
            % Calculation of NEIGHBORS KRILL effect
            numberneighbours=0;%% 
            maximundistance = mean(Rkrill)/5;% MAximun distance of neighbours
            alpha_n = 0;%alpha local
            for otherkrill=1:NumberKrills
                if and(Rkrill<maximundistance,otherkrill~=krill)%if its in the distance
                    numberneighbours=numberneighbours+1;
                    if and(numberneighbours<=4,K(otherkrill)~=K(krill))
                        alpha_n = alpha_n-(K(otherkrill) - K(krill)) /Kworst_Kbest/ Rkrill(otherkrill) * Rkrillkrill(:,otherkrill);
                    end
                end
            end
            % Movement Induced => N=Nmax*alpha+w*N
            N(:,krill) = w*N(:,krill)+Nmax*(alpha_b+alpha_n);
      % % % % % % % % % % % % % Foraging Motion % % % % % % % % % %
      %% Calculation of FOOD attraction
            if Kfood(iteration) < K(krill)%if the food has best value(lower), we go there
                Beta_f=-2*(1-iteration/IterationMax)*(Kfood(iteration) - K(krill)) /Kworst_Kbest/ sqrt(sum(Rfood.*Rfood)) * Rfood;
            else
                Beta_f=0;
            end
            % Calculation of BEST psition attraction
            Rold = Xold(:,krill)-X(:,krill);
            if Kold(krill) < K(krill) % If we were in better position before....goes back
                Beta_b=-(Kold(krill) - K(krill)) /Kworst_Kbest/ sqrt(sum(Rold.*Rold)) *Rold;
            else
                Beta_b=0;
            end
            %%  Foraging Motion =>F=Vf*beta+w*F
            F(:,krill) = w*F(:,krill)+Vf*(Beta_b+Beta_f);
            % % % % % % % % % % % % % Physical Diffusion % % % % % % % % %
            %%
            D = Dmax*(1-iteration/IterationMax)*floor(rand+(K(krill)-Kbest(iteration,numberRun))/Kworst_Kbest)*(2*rand(NumberParameters,1)-ones(NumberParameters,1));
            %% FINAL FORMULA=>dz=N+F+D
            % % % % % % % % % % % % % Motion Process % % % % % % % % % % %
            Dt = mean(abs(UpperLimit-LowerLimit))/2;%scale factor
            %DX = Dt*(N(:,krill)+F(:,krill));           
            DX = Dt*(N(:,krill)+F(:,krill)+D); 
 %%  % % % % % % % % % % % Crossover % % % % % % % % % % % % %
 
            if C_flag ==1
                C_rate = 0.8 + 0.2*(K(krill)-Kbest(iteration,numberRun))/Kworst_Kbest;
                Cr = rand(NumberParameters,1) < C_rate ;
                % Random selection of Krill No. for Crossover
                NK4Cr = round(NumberKrills*rand+.5);  
                % Crossover scheme
                X(:,krill)=X(:,NK4Cr).*(1-Cr)+X(:,krill).*Cr;
            end
%%  % % % % % % % % % % % Mutation % % % % % % % % % % % % %
            if M_flag==1
                random=rand;
                if random< 1/NumberKrills%possibiliy of mutation
                M_rate = 0.6 + 0.4*(K(krill)-Kbest(iteration,numberRun))/Kworst_Kbest;
                Mr = rand(NumberParameters,1) < M_rate ;
                RandomValues = rand(NumberParameters,1);
                X(:,krill)=RandomValues.*(1-Mr)+X(:,krill).*Mr;
                end
            end
            
 
 
            % Update the position
            X(:,krill)=X(:,krill)+DX;
            X(:,krill)=findlimits(X(:,krill)',LowerLimit,UpperLimit,Xbest(:,iteration,numberRun)'); % Bounds Checking

            % With weights , create a network to know error <==== FITNESS
            [net] = createNet( X(:,krill),neurons,P,T,net ); 
            output=sim(net,P);
%output=net(P);
            K(krill)=fitness(net,T,output);%%<============FITNESS=================
            %K(krill)=fitness(X(:,krill));%%<============FITNESS=================
            if K(krill)<Kold(krill)
                Kold(krill)=K(krill);
                Xold(:,krill)=X(:,krill);
            end
                        
        end
% Update the current best
        [Kbest(iteration+1,numberRun) A] = min(K);
        if Kbest(iteration+1,numberRun)<Kbest(iteration,numberRun)
            Xbest(:,iteration+1,numberRun) = X(:,A);
        else
            Kbest(iteration+1,numberRun) = Kbest(iteration,numberRun);
            Xbest(:,iteration+1,numberRun) = Xbest(:,iteration,numberRun);
        end
        
        %% Storing
        [F_i(iteration,numberRun) H] = min(K);
        X_i(:,iteration,numberRun) = X(:,H);
        F_min_I(iteration,numberRun) = mean(K);
        
  
 
end%End of iteration
end%End of number runs
name=strcat('Selecting the Best Run...',Ticker);
waitbar(1 ,h,name);

%% Post-Processing => selects best Run
[Best O] = min(Kbest(end,:));
Xbest(:,end,O);
Mean = mean(Kbest(end,:));
Worst = max(Kbest(end,:));
SD = std(Kbest(end,:));
if Kbest(end,:)< Kinitial
    fprintf('We got Better Value \n');
end
%% Show result
fprintf('The Min value is ');
fprintf(num2str(Best));
fprintf(', in ( ');

for parameters=1:NumberParameters
fprintf(num2str(Xbest(parameters,end,O)));
% With weights , create a network to know error <==== FITNESS
if parameters<NumberParameters
fprintf(', ');
end
end
fprintf(') \n');
if Best< Kinitial
    fprintf('We change weights \n');
end
net = createNet( Xbest(:,end,O),neurons,P,T,net );
%% plots the best
% subplot 312
%     hold on
%     coordenate1=(Xbest(1,end,O)-LowerLimit(1)+1)/step;%iteration
%     coordenate2=(Xbest(2,end,O)-LowerLimit(2)+1)/step;
%     plot(coordenate1,coordenate2, 'ro');%X(1,:)
%     hold off

%% Convergence plot of the best run
%figure
% subplot 311
% semilogy(1:IterationMax+1,Kbest(:,O),1:IterationMax+1,mean(Kbest'))
% xlabel('{\itNo. of Iterations}')
% ylabel('{\itf}({\bfx_{best}})')
% legend('Best run values','Average run values')


close(h)%close waitbar

end

